package com.example.new8.presenter;

import android.content.Context;
import android.util.Log;


import com.example.new8.contract.WeatherContact;
import com.example.new8.entity.Weather;
import com.example.new8.service.WeatherService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class WeatherPresenter implements WeatherContact.WeatherPresenter{
    private WeatherContact.WeatherView mMainView;
    private Context mContext;
    public WeatherPresenter(WeatherContact.WeatherView mMainView , Context mContext)
    {
        this.mMainView = mMainView;
        this.mContext = mContext;
    }
    @Override
    public void getData(String city) {
        Log.d("城市名", "city: " + city);
        String url = "https://api.oioweb.cn/api/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
        WeatherService service = retrofit.create(WeatherService.class);
        Log.d("已经运行到此处", "==================================");
        service.getData(city)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<Weather>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Log.d("已经运行到这里", "！！！！！！！！！！！！！！！！！！！！！！！！ ");
                    }

                    @Override
                    public void onNext(@NonNull Weather weather) {

                        if (mMainView != null){
                            mMainView.showData(weather);
                        } else {
                            Log.e("空指针警告", "mMainView 为 null");
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("错误处理", "数据获取失败: " + e.getMessage());
                        // 可以在此处通知用户或尝试重新加载数据
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
